﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data.SQLite;
using System.Configuration;
using System.Text;

namespace XMas.WebAPI.Controllers
{
    public class GameController : ApiController
    {
        private readonly string _connString = ConfigurationManager.ConnectionStrings["defaultConn"].ConnectionString;
        private readonly string _highestScoreId = "FEA491B2-2536-406C-A80F-4C999A6C03F7";

        //[Route("api/scores")]
        public HttpResponseMessage Get()
        {
            using(var conn = new SQLiteConnection(_connString))
            {
                conn.Open();
                using(var command = new SQLiteCommand(conn))
                {
                    command.CommandText = "SELECT Score FROM Scores where Id = @Id";
                    command.Parameters.Add(new SQLiteParameter("@Id", _highestScoreId));
                    var result = command.ExecuteScalar();                    
                    var resp = new HttpResponseMessage(HttpStatusCode.OK);
                    resp.Content = new StringContent(result.ToString(), Encoding.UTF8, "text/plain");
                    return resp;
                }
            }            
        }
        
        [HttpPost]
        public void Post(int score)
        {
            using (var conn = new SQLiteConnection(_connString))
            {
                conn.Open();
                using (var command = new SQLiteCommand(conn))
                {
                    command.CommandText = "UPDATE Scores SET Score = @score WHERE Score < @score AND Id = @Id";
                    command.Parameters.Add(new SQLiteParameter("@Id", _highestScoreId));
                    command.Parameters.Add(new SQLiteParameter("@score", score));
                    var result = command.ExecuteNonQuery();
                }
            }
        }
    }
}